<template>
  <div>

    <BasicTable @register="registerTable" @row-db-click="rowdblClick">
      <template #form-custom> custom-slot </template>
      <template #toolbar>
        <!-- <a-button type="primary" @click="getFormValues">获取表单数据</a-button> -->
      </template>
      <template #tableTitle>
        <div>

          <a-button type="primary" @click="addOpenFormDialog" preIcon="mdi:plus-circle-outline">
            新增</a-button>
        </div>
      </template>
      <!-- <template #bodyCell="{column}">
        <span v-if="column.dataIndex !== 'action'">{{  }}</span>
      </template> -->
      <template #action="{ record }">
        <TableAction  stop-button-propagation :actions="[
          {
            label: '进入',
            color: 'success',
            icon: 'mdi:pencil',
            
            onClick: () => gotoWorkspacePage(record),
          },
          {
            label: '编辑',
            icon: 'mdi:pencil',
            onClick: handleRowEdit.bind(null, record),
          },
          {
            label: '删除',
            icon: 'mdi:delete',
            color: 'error',
            popConfirm: {
              title: '是否确认删除',
              confirm: handleRowDelete.bind(null, record),
              cancel: handleRowCancel.bind(null, record),
            },
          },
        ]" />
      </template>
    </BasicTable>
    <BasicModal @register="registerModal" title="新增/修改" :show-ok-btn="false" :help-message="[]"
      @openChange="modalVisibleChange">
      <template #footer></template>
      <BasicForm @register="registerAddUpdateForm" autoFocusFirstItem :labelWidth="80" :schemas="addUpdateFormSchemas"
        :actionColOptions="{ span: 24 }" :showActionButtonGroup='true' :submitButtonOptions="{ text: '保 存' }"
        @submit="handleSubmit" @reset="handleReset">
        <!-- <template #selectA="{ model, field }">
          <Select :options="[]" mode="multiple" v-model:value="model[field]" allowClear />
        </template> -->


      </BasicForm>
    </BasicModal>
  </div>
</template>
<script lang="ts" setup>
  import { BasicColumn, BasicTable, FormProps, FormSchema, useTable, TableAction } from '@/components/Table';
  import { DatasourcesObject, deleteOneDatasourcesRecord, getDatasourcesList, saveOneDatasourcesRecord } from "@/api/goMyAdmin"
  import { BasicModal, useModal } from '@/components/Modal';
  import { BasicForm } from "@/components/Form"
  import { useForm } from '@/components/Form';
  import { message } from 'ant-design-vue';
  import { nextTick, ref } from 'vue';
  import { router } from '@/router';



  function getBasicColumns(): BasicColumn[] {
    return [
      {
        title: 'ID',
        dataIndex: 'ID',
        fixed: 'left',
        width: 70,
      },
      {
        title: '名称',
        dataIndex: 'name',
        width: 150,
        // filters: [
        //   { text: 'Male', value: 'male' },
        //   { text: 'Female', value: 'female' },
        // ],
      },
      {
        title: '数据库类型',
        dataIndex: 'driver',
        width: 150,
        // filters: [
        //   { text: 'Male', value: 'male' },
        //   { text: 'Female', value: 'female' },
        // ],
      },
      {
        title: '主机',
        dataIndex: 'ip',
      },
      {
        title: '端口',
        dataIndex: 'port',
        // width: 150,
        sorter: false,
        // defaultHidden: true,
      },
      {
        title: '用户名',
        // width: 150,
        sorter: false,
        dataIndex: 'user',
      },
      {
        title: '密码',
        // width: 150,
        sorter: false,
        dataIndex: 'password',
      },
      {
        title: '数据库',
        // width: 150,
        sorter: true,
        dataIndex: 'database',
      },

    ];
  }
  function createSearchFormConfig(): Partial<FormProps> {
    return {
      labelWidth: 100,
      schemas: [
        {
          field: `name`,
          label: `名称`,
          // slot: 'custom',
          component: 'Input',
          colProps: {
            xl: 12,
            xxl: 8,
          },
        },
      ],
    };
  }


  const [registerTable, table] = useTable({
    title: '服务器',
    api: getDatasourcesList,
    columns: getBasicColumns(),
    actionColumn: {
      title: '操作',
      // width: 150,
      sorter: false,
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
    useSearchForm: true,
    formConfig: createSearchFormConfig(),
    showTableSetting: false,
    tableSetting: { fullScreen: false },
    showIndexColumn: true,
    rowKey: 'ID',
    maxHeight: 300,
    rowSelection: {
      type: 'checkbox',
    },
    showSelectionBar: true, // 显示多选状态栏
  });

  function getFormValues() {
    console.log(table.getForm().getFieldsValue());
  }

  const rowdblClick = (row) => {
    // console.log(row);
    handleRowEdit({ ...row })
  }

  /** 新增或修改 打开表单弹窗 */
  const addOpenFormDialog = () => {
    auModal.openModal()
  }


  const [registerModal, auModal] = useModal();

  const modalVisibleChange = async (visible: boolean) => {
    // console.log(visible);
    // 关闭之后清空表单
    if (!visible) {
      nextTick(() => {
        form.resetFields();
      })
    }
  }

  const addUpdateFormSchemas: FormSchema[] = [
    // {
    //   field: 'divider-basic',
    //   component: 'Divider',
    //   label: '基础字段',
    //   colProps: {
    //     span: 24,
    //   },
    // },

    {
      field: 'name',
      component: 'Input',

      label: ({ model }) => {
        return `名称`;
      },
      colProps: {
        span: 24,
      },
      // can func
      componentProps: ({ schema, formModel }) => {
        // console.log('form:', schema);
        // console.log('formModel:', formModel);
        return {
          placeholder: '请输入名称',
          onChange: (e) => {
            // console.log(e);
          },
        };
      },
      // renderComponentContent: () => {
      //   return {
      //     prefix: () => 'pSlot',
      //     suffix: () => 'sSlot',
      //   };
      // },
      rules: [
        { required: true, message: '必填项' }
      ]
    },
    {
      field: 'driver',
      component: 'Input',

      label: ({ model }) => {
        return `数据库类型`;
      },
      colProps: {
        span: 24,
      },
      // can func
      componentProps: ({ schema, formModel }) => {
        // console.log('form:', schema);
        // console.log('formModel:', formModel);
        return {
          placeholder: '请输入数据库类型',
          onChange: (e) => {
            // console.log(e);
          },
        };
      },
      // renderComponentContent: () => {
      //   return {
      //     prefix: () => 'pSlot',
      //     suffix: () => 'sSlot',
      //   };
      // },
      rules: [
        { required: true, message: '必填项' }
      ]
    },
    {
      field: "ip",
      label: "主机",

      component: "Input",
      componentProps: {
        placeholder: "请输入服务器主机地址"
      },
      colProps: {
        span: 24
      },
      rules: [
        { required: true, message: '必填项' }
      ]
    },
    {
      field: "port",
      label: "端口",

      component: "InputNumber",
      componentProps: {
        placeholder: "请输入服务器主机端口"
      },
      colProps: {
        span: 24
      },
      rules: [
        { required: true, message: '必填项' }
      ]
    },
    {
      field: "user",
      label: "用户",

      component: "Input",
      componentProps: {
        placeholder: "请输入数据库用户"
      },
      colProps: {
        span: 24
      },
      rules: [
        { required: true, message: '必填项' }
      ]
    },
    {
      field: "password",
      label: "密码",

      component: "Input",
      componentProps: {
        placeholder: "请输入数据库密码"
      },
      colProps: {
        span: 24
      },
      rules: [
        { required: true, message: '必填项' }
      ]
    },
    {
      field: "database",
      label: "默认数据库",

      component: "Input",
      componentProps: {
        placeholder: "请输入默认数据库"
      },
      colProps: {
        span: 24
      },

    }


  ];

  const [registerAddUpdateForm, form] = useForm();

  const handleSubmit = async (data) => {
    console.log(data);
    currentEditRow.value = { ...currentEditRow.value, ...data }
    await saveOneDatasourcesRecord(currentEditRow.value as any)
    message.success("保存成功！")
    auModal.closeModal()
    form.resetFields();
    await table.reload();
  }
  const handleReset = async () => {

  }

  const currentEditRow = ref({})

  const handleRowEdit = async (record: DatasourcesObject) => {
    currentEditRow.value = record;
    auModal.openModal()
    nextTick(() => {
      form.setFieldsValue({
        ...record
      })
    })

  }
  const handleRowDelete = async (record: DatasourcesObject) => {
    await deleteOneDatasourcesRecord({ id: record.ID })
    message.success("保存成功！")
    await table.reload();
  }
  const handleRowCancel = async (record: DatasourcesObject) => { }

  /** 前往工作空间 */
  const gotoWorkspacePage = async (record: DatasourcesObject) => {
    // todo
    console.log(record);
    router.push({ path: "/gma/workspace", query: { dsId: record.ID ,dsName:record.name} })
  }

</script>
